package com.xmzs.web.controller;


import com.xmzs.common.chat.domain.request.SaveMsgRequest;
import com.xmzs.common.chat.entity.chat.BaseChatCompletion;
import com.xmzs.common.chat.entity.chat.ChatCompletion;
import com.xmzs.common.chat.domain.request.ChatRequest;
import com.xmzs.common.chat.utils.TikTokensUtil;
import com.xmzs.web.service.ChatService;
import com.xmzs.web.service.SseService;
import jakarta.servlet.http.HttpServletResponse;
import jakarta.validation.Valid;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.servlet.mvc.method.annotation.ResponseBodyEmitter;

/**
 * 描述：
 *
 * @author https:www.unfbx.com
 * @date 2023-03-01
 */
@Controller
@Slf4j
@RequiredArgsConstructor
public class ChatController {

    private final SseService sseService;

    private final ChatService chatService;

    /**
     * 聊天接口
     */
    @CrossOrigin
    @PostMapping("/chat")
    @ResponseBody
    public ResponseBodyEmitter sseChat(@RequestBody @Valid ChatRequest chatRequest, HttpServletResponse response) {
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        return sseService.sseChat(chatRequest);
    }

    @CrossOrigin
    @PostMapping("/saveMsg")
    @ResponseBody
    public void saveMsg(@RequestBody @Valid SaveMsgRequest saveMsgRequest) {
        if (ChatCompletion.Model.GPT_4_1106_PREVIEW.getName().equals(saveMsgRequest.getModel())) {
            // 扣除tokens
            int tokens = TikTokensUtil.tokens(BaseChatCompletion.Model.GPT_4_0613.getName(), saveMsgRequest.getMsg()) / 2;
            chatService.deductToken(tokens);
        }
    }


}
